import React, { useState, useEffect, useCallback } from 'react';
import { Tooltip } from 'antd';

interface UnitInfoStatusBadgesProps {
    unitId: string;
    unitInfo?: any;
    statisticsData?: any;
}

const UnitInfoStatusBadges: React.FC<UnitInfoStatusBadgesProps> = ({ unitId, unitInfo, statisticsData }) => {
    const [scanRecords, setScanRecords] = useState<any>(null);
    const [loading, setLoading] = useState(false);

    // 加载最新扫描记录
    const loadLatestScanRecords = useCallback(async () => {
        if (!unitId) return;
        setLoading(true);
        try {
            const { fetchScanTaskList } = await import('../../../services/scanTask');
            const result = await fetchScanTaskList({
                unitId,
                pageNum: 1,
                pageSize: 10,
                orderBy: 'start_time',
                orderDirection: 'DESC'
            });

            const latestByType: any = {};
            if (result?.records) {
                result.records.forEach((record: any) => {
                    const taskType = record.taskType;
                    if (!latestByType[taskType] ||
                        new Date(record.startTime) > new Date(latestByType[taskType].startTime)) {
                        latestByType[taskType] = record;
                    }
                });
            }
            setScanRecords(latestByType);
        } catch (error) {
            console.error('加载扫描记录失败:', error);
        } finally {
            setLoading(false);
        }
    }, [unitId]);

    useEffect(() => {
        loadLatestScanRecords();
    }, [loadLatestScanRecords]);

    const formatRelativeTime = (dateStr: string) => {
        if (!dateStr) return '未扫描';
        const date = new Date(dateStr);
        const now = new Date();
        const diff = now.getTime() - date.getTime();
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        const hours = Math.floor(diff / (1000 * 60 * 60));
        const minutes = Math.floor(diff / (1000 * 60));

        if (days > 0) return `${days}天前`;
        if (hours > 0) return `${hours}小时前`;
        if (minutes > 0) return `${minutes}分钟前`;
        return '刚刚';
    };

    const getStatusInfo = (status: string) => {
        const statusMap: any = {
            'AVAILABLE': { color: '#52c41a', bgColor: '#f6ffed', borderColor: '#b7eb8f', icon: '✓', label: '可用' },
            'SUCCESS': { color: '#52c41a', bgColor: '#f6ffed', borderColor: '#b7eb8f', icon: '✓', label: '成功' },
            'RUNNING': { color: '#1890ff', bgColor: '#e6f7ff', borderColor: '#91d5ff', icon: '⟳', label: '运行中' },
            'PROCESSING': { color: '#1890ff', bgColor: '#e6f7ff', borderColor: '#91d5ff', icon: '⟳', label: '处理中' },
            'FAILED': { color: '#ff4d4f', bgColor: '#fff2f0', borderColor: '#ffccc7', icon: '✗', label: '失败' },
            'PENDING': { color: '#faad14', bgColor: '#fffbe6', borderColor: '#ffe58f', icon: '⋯', label: '等待中' },
            'UNAVAILABLE': { color: '#d9d9d9', bgColor: '#fafafa', borderColor: '#d9d9d9', icon: '○', label: '不可用' }
        };
        return statusMap[status] || { color: '#d9d9d9', bgColor: '#fafafa', borderColor: '#d9d9d9', icon: '?', label: '未知' };
    };

    const dataTypes = [
        { key: 'JAR', label: 'JAR', fullLabel: 'JAR扫描', enabled: unitInfo?.jarTask, dataStatus: statisticsData?.jarDataStatus, lastTime: statisticsData?.jarTaskLastTime },
        { key: 'GIT', label: 'Git', fullLabel: 'Git扫描', enabled: unitInfo?.gitTask, dataStatus: statisticsData?.gitDataStatus, lastTime: statisticsData?.gitTaskLastTime },
        { key: 'SA', label: 'SA', fullLabel: 'SA扫描', enabled: unitInfo?.saTask, dataStatus: statisticsData?.saDataStatus, lastTime: statisticsData?.saTaskLastTime },
        { key: 'APM', label: 'APM', fullLabel: 'APM扫描', enabled: unitInfo?.apmTask, dataStatus: statisticsData?.apmDataStatus, lastTime: statisticsData?.apmTaskLastTime },
        { key: 'JACG', label: 'JACG', fullLabel: 'JACG调用图分析', enabled: unitInfo?.jacgTask, dataStatus: statisticsData?.jacgDataStatus, lastTime: statisticsData?.jacgTaskLastTime },
        { key: 'DB', label: 'DB', fullLabel: 'DB数据库分析', enabled: unitInfo?.dbTask, dataStatus: statisticsData?.dbDataStatus, lastTime: statisticsData?.dbTaskLastTime }
    ];

    return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
            {dataTypes.map(type => {
                const record = scanRecords?.[type.key];
                const isEnabled = type.enabled !== false;
                const dataStatus = type.dataStatus || (record ? record.status : null);
                const statusInfo = dataStatus ? getStatusInfo(dataStatus) : null;
                const lastTime = type.lastTime || (record ? record.startTime : null);

                if (!isEnabled) {
                    return (
                        <Tooltip key={type.key} title="未启用">
                            <div style={{
                                padding: '2px 6px',
                                borderRadius: '3px',
                                background: '#fafafa',
                                border: '1px solid #f0f0f0',
                                fontSize: '11px',
                                color: '#bfbfbf',
                                opacity: 0.6
                            }}>
                                {type.label}
                            </div>
                        </Tooltip>
                    );
                }

                return (
                    <Tooltip
                        key={type.key}
                        title={
                            <div style={{ fontSize: '11px' }}>
                                <div style={{ fontWeight: '600', marginBottom: '2px' }}>{type.fullLabel}</div>
                                <div>状态: {statusInfo?.label || '未扫描'}</div>
                                <div>更新: {lastTime ? formatRelativeTime(lastTime) : '未扫描'}</div>
                            </div>
                        }
                    >
                        <div style={{
                            padding: '2px 6px',
                            borderRadius: '3px',
                            background: statusInfo?.bgColor || '#fafafa',
                            border: `1px solid ${statusInfo?.borderColor || '#f0f0f0'}`,
                            fontSize: '11px',
                            color: statusInfo?.color || '#8c8c8c',
                            fontWeight: '500',
                            cursor: 'pointer',
                            transition: 'all 0.2s ease',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '3px'
                        }}>
                            <span>{type.label}</span>
                            {statusInfo && <span style={{ fontSize: '12px' }}>{statusInfo.icon}</span>}
                        </div>
                    </Tooltip>
                );
            })}
        </div>
    );
};

export default UnitInfoStatusBadges;
